//
//  QianliVpnManager.swift
//  todoios
//
//  Created by qianli on 2025/4/25.
//

import Foundation
import Combine
import NetworkExtension

public final class QianliVpnManager: ObservableObject {
    private var rwuccngmPUqYUiwY: Set<AnyCancellable> = []
    private var NVBpGrDXarC6Lgrc: ((_ status: NEVPNStatus) -> Void)?
    public var controller: QianliVPNController?    
    public static let shared = QianliVpnManager()
    public var vpnStatus: NEVPNStatus = .invalid
    private let bOS0gdw1xX1WCpf3: String = {
        return "\(Bundle.main.bundleIdentifier!).PacketTunnel"
    }()
    
    private init() {
//        当 VPN 配置发生变化时，调用 handleVPNConfigurationChangedNotification 方法
        NotificationCenter.default
            .publisher(for: .NEVPNConfigurationChange, object: nil)
            .receive(on: DispatchQueue.main)
            .sink { [unowned self] in self.QLlqxc7XLBLM7Sfk($0) }
            .store(in: &self.rwuccngmPUqYUiwY)
        
//        当 VPN 状态发生变化时，调用 handleVPNStateChangeNotification 方法
        NotificationCenter.default
            .publisher(for: .NEVPNStatusDidChange)
            .receive(on: DispatchQueue.main)
            .sink { [unowned self] in self.UcU32yF7QEzdvDck($0) }
            .store(in: &self.rwuccngmPUqYUiwY)
    }
    
// 当 VPN 配置发生变化时的处理
    private func QLlqxc7XLBLM7Sfk(_ notification: Notification) {
        Task(priority: .high) {
// 当接收到 NEVPNConfigurationChange 通知时，创建一个高优先级的异步任务，调用 loadController 方法重新加载 VPNController。
            let _ = await self.M3Ll8cXUeFZ1dQDX()
        }
    }
    
    func M3Ll8cXUeFZ1dQDX() async -> QianliVPNController? {
        let manager = await self.HiE3FC0BNQBHBbB4()
        if (manager == nil) {
            self.controller = nil //没找到vpn配置
        } else {
            if self.controller?.isEqually(manager: manager!) ?? false {
                // Nothing
            } else {
                self.controller = QianliVPNController(providerManager: manager!)
            }
        }
        return self.controller
    }
    
    private func HiE3FC0BNQBHBbB4() async -> NETunnelProviderManager? {
        let managers = try? await NETunnelProviderManager.loadAllFromPreferences()
//        获取所有的 VPN 配置
        if (managers == nil) {
            return nil
        }
        
// 筛选出匹配特定包标识符的配置，managers!.first(where:) 是一个高阶函数，其作用是在 managers 数组里查找第一个满足特定条件的元素。
        let first = managers!.first { manager in
            guard let configuration = manager.protocolConfiguration as? NETunnelProviderProtocol else {
                return false
            }
            return configuration.providerBundleIdentifier == self.bOS0gdw1xX1WCpf3
        }
        
        do {
            guard let first = first else {
                return nil
            }
            try await first.loadFromPreferences()
            return first
        } catch {
            debugPrint(error.localizedDescription)
            return nil
        }
    }
    
    public func uc134OWEq85miEpc(listen: @escaping (_ status: NEVPNStatus) -> Void) {
        self.NVBpGrDXarC6Lgrc = listen
    }
    
// 当 VPN 状态发生变化时的处理
    private func UcU32yF7QEzdvDck(_ notification: Notification) {
        let connection = notification.object as? NEVPNConnection
        if (connection == nil) {
            return
        }
        if (connection!.status == .disconnected) {
            self.controller = nil
        }
        vpnStatus = connection!.status
        self.NVBpGrDXarC6Lgrc?(connection!.status)
    }
    
    public func aYrafiM1uaq29ytv() async throws {
//      从系统偏好设置中加载所有的 VPN 配置，并筛选出与特定包标识符匹配的 NETunnelProviderManager 实例,如果返回nil，则NETunnelProviderManager()创建一个实例
        let manager = (await HiE3FC0BNQBHBbB4()) ?? NETunnelProviderManager()
        let config = NETunnelProviderProtocol()
        config.providerBundleIdentifier = self.bOS0gdw1xX1WCpf3
        config.serverAddress = "127.0.0.1" //"localhost"
        config.disconnectOnSleep = false   //设置当设备进入睡眠状态时，VPN 连接不会断开
        config.providerConfiguration = [:] //设置 VPN 提供商的自定义配置，这里使用一个空字典表示没有自定义配置。
        
        manager.protocolConfiguration = config
        manager.localizedDescription = QianliAppEnvStruct.appName //在系统vpn配置中显示的vpn名称,可任意
        manager.isEnabled = true         //启用 VPN 配置，使 VPN 可以被使用
//        manager.isOnDemandEnabled = true //启用按需连接功能，当设备满足特定条件时，自动连接 VPN
        try await manager.saveToPreferences()
    }
    
    public func y4On03TpAsKs4W4W(msg:String) async{
        let _ = await self.M3Ll8cXUeFZ1dQDX()
        if let controller = self.controller{
            if let message = msg.data(using: .utf8){
                if let response = await controller.sendMessage2Provider(message){
                    print("send msg: \(msg)\n response = \(String(describing: String(data:response,encoding: .utf8)))")
                }
            }
        }
    }
    
}
